package com.smartdot.bluetoothidcarddemo.http;


import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Predicate;
import io.reactivex.schedulers.Schedulers;
import io.reactivex.subjects.PublishSubject;

/**
 * 线程切换
 * Created by LUOLI on 2017/3/06.
 */
public class DefaultTransformer<T> implements ObservableTransformer<T, T> {
    private LifeCycleEvent event;
    private PublishSubject<LifeCycleEvent> lifecycleSubject;
    public DefaultTransformer(LifeCycleEvent event, PublishSubject<LifeCycleEvent> lifecycleSubject) {
        this.event = event;
        this.lifecycleSubject = lifecycleSubject;
    }

    @Override
    public ObservableSource<T> apply(@NonNull Observable<T> upstream) {
        Observable<T> tObservable = upstream
                .takeUntil(getLifeCycleObservable(event, lifecycleSubject))
                .retryWhen(new RetryFunction(3, 3))
                .subscribeOn(Schedulers.io())//指定网络请求在io后台线程中进行
                .observeOn(AndroidSchedulers.mainThread());//指定observer回调在UI主线程中进行
        return tObservable;
    }
    /**
     * 获取用于控制声明周期的Observable
     */
    public static Observable<LifeCycleEvent> getLifeCycleObservable(final LifeCycleEvent event, PublishSubject<LifeCycleEvent> lifecycleSubject) {
        return lifecycleSubject.filter(new Predicate<LifeCycleEvent>() {
            @Override
            public boolean test(LifeCycleEvent lifeCycleEvent) throws Exception {
                //当生命周期为event状态时，发射事件
                return lifeCycleEvent.equals(event);
            }
        }).take(1);
    }
}
